<template>
  <div class="repair-workorder-container">
    <el-card>
      <h2>待上门服务工单</h2>

      <!-- 工单列表 -->
      <el-table
        :data="workOrderList"
        border
        stripe
        v-loading="isLoading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="_id" label="工单编号" width="180" />
        <el-table-column prop="customer_name" label="客户姓名" width="120" />
        <el-table-column prop="customer_phone" label="联系电话" width="150" />
        <el-table-column prop="user_claim" label="问题描述" min-width="200" />
        <el-table-column prop="appointment_time" label="预约时间" width="180" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleCompleteRepair(scope.row)"
              :disabled="scope.row.status !== '待上门服务'"
            >
              完成维修
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 完成维修模态框 -->
      <el-dialog
        v-model="showCompleteDialog"
        title="填写维修结果"
        width="40%"
        :before-close="handleDialogClose"
      >
        <el-form :model="repairForm" :rules="repairRules" label-width="80px">
          <el-form-item label="检查结果" prop="repair_inspection">
            <el-input
              v-model="repairForm.repair_inspection"
              type="textarea"
              :rows="3"
              placeholder="请描述检查情况"
            />
          </el-form-item>
          <el-form-item label="维修结果" prop="repair_result">
            <el-input
              v-model="repairForm.repair_result"
              type="textarea"
              :rows="3"
              placeholder="请描述维修结果"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showCompleteDialog = false">取消</el-button>
            <el-button type="primary" @click="confirmComplete" :loading="isSubmitting">
              提交结果
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getWorkOrdersByStatus } from '@/api/workOrder' // 按状态获取工单接口
import { completeRepairByRepairman } from '@/api/workOrder' // 完成维修接口
import { ElMessage } from 'element-plus'

// 状态管理
const workOrderList = ref([]) // 待上门服务工单列表
const isLoading = ref(false) // 工单加载状态
const showCompleteDialog = ref(false) // 完成维修模态框显示状态
const repairForm = ref({
  // 维修结果表单
  repair_inspection: '',
  repair_result: '',
})
const currentOrderId = ref('') // 当前操作的工单ID
const isSubmitting = ref(false) // 提交加载状态

// 表单校验规则
const repairRules = ref({
  repair_inspection: [{ required: true, message: '请填写检查结果', trigger: 'blur' }],
  repair_result: [{ required: true, message: '请填写维修结果', trigger: 'blur' }],
})

// 初始化：加载待上门服务工单（状态为'pending_service'）
onMounted(async () => {
  isLoading.value = true
  try {
    const res = await getWorkOrdersByStatus({ status: '待上门服务' })
    if (res.code === 200) {
      workOrderList.value = res.data.map((item) => ({
        ...item,
        appointmentTime: new Date(item.appointment_time).toLocaleString(), // 格式化时间
      }))
    }
  } catch (err) {
    ElMessage.error('获取待上门工单失败', err)
  } finally {
    isLoading.value = false
  }
})

// 点击完成维修按钮
const handleCompleteRepair = (row) => {
  currentOrderId.value = row._id // 假设工单数据包含_id字段
  repairForm.value = { repair_inspection: '', repair_result: '' } // 重置表单
  showCompleteDialog.value = true
}

// 确认提交维修结果
const confirmComplete = async () => {
  if (!currentOrderId.value) return

  isSubmitting.value = true
  try {
    const res = await completeRepairByRepairman(currentOrderId.value, {
      ...repairForm.value,
      repairman_id: JSON.parse(localStorage.getItem('userInfo'))._id, // 从localStorage获取维修员ID
    })
    if (res.code === 200) {
      ElMessage.success('维修结果提交成功')
      showCompleteDialog.value = false
      // 刷新工单列表
      const freshRes = await getWorkOrdersByStatus({ status: '待上门服务' })
      workOrderList.value = freshRes.data.map((item) => ({
        ...item,
        appointmentTime: new Date(item.appointment_time).toLocaleString(),
      }))
    } else {
      ElMessage.error(res.message || '提交失败')
    }
  } catch (err) {
    ElMessage.error('网络请求失败', err)
  } finally {
    isSubmitting.value = false
  }
}

// 关闭模态框
const handleDialogClose = () => {
  showCompleteDialog.value = false
  currentOrderId.value = ''
}
</script>

<style scoped>
.repair-workorder-container {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.dialog-footer {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>
